package com.guava;

import com.google.common.base.Throwables;

/**
 * ThrowablesTester--GuavaTest
 *
 * @author: Jovi
 * @createTime: 2018-05-08 14:39
 **/
public class ThrowablesTester {

    public static void main(String[] args) {

        ThrowablesTester tester = new ThrowablesTester();
        try {
            tester.showCaseThrowables();
        } catch (InvalidInputException e) {
            System.out.println(Throwables.getRootCause(e));//返回抛出的最里面的原因。
        } catch (Exception e) {
            System.out.println(Throwables.getStackTraceAsString(e));//返回包含toString()的结果字符串，随后完整抛出，递归的堆栈跟踪
        }


        try {
            tester.showCaseThrowables1();
        } catch (Exception e) {
            System.out.println(Throwables.getStackTraceAsString(e));
        }
    }

    public void showCaseThrowables() throws InvalidInputException {

        try {
            sqrt(-3.0);
        } catch (Throwable e) {
            Throwables.propagateIfPossible(e, InvalidInputException.class);//传播抛出对象完全按原样，当且仅当它是RuntimeException或Error的一个实例
        }
    }

    private double sqrt(double input) throws InvalidInputException {

        if(input<0) throw new InvalidInputException();
        return Math.sqrt(input);
    }

    private void showCaseThrowables1() {
        int[] data = {1, 2, 3};
        try {
            getValue(data, 4);
        } catch (Throwable e) {
            Throwables.propagateIfPossible(e,IndexOutOfBoundsException.class);
        }
    }

    private double getValue(int [] list, int index) throws IndexOutOfBoundsException{
        return list[index];
    }

}

class InvalidInputException extends Exception {

}
